from faiss import logger
from flask import Blueprint, request, jsonify, abort
from flask import Flask, jsonify, request, render_template
from flask_login import current_user
from flask_mqtt import Mqtt
import uuid
import json
from datetime import datetime

from app import db
from app.function import check_and_execute_rules

from app.iot_mqtt.command import command
from app.iot_mqtt.iot_funciton import set_device_properties
from app.models import SystemRoles, Conversation, Message, Device, DeviceCommand

bp = Blueprint('control', __name__)

auto_rules = []
current_id = 0

scheduled_tasks = []


# scheduler = BackgroundScheduler()

@bp.route('/remote_control', methods=['POST'])
def remote_control():
    """远程控制设备"""
    data = request.get_json()
    logger.info(f"接收到的数据: {data}")
    if 'paras' in data:
        data = data['paras']
    try:
        valid_keys = ['gather', 'open_fan', 'open_water', 'open_led', 'led_red', 'led_blue', 'led_green', 'id',
                      'command_name', 'service_id']
        if not any(key in data for key in valid_keys):
            logger.error("无效的设备参数")
            return jsonify({'status': 'error', 'message': '无效的设备参数'}), 400

        device_id = data.get('id')
        if not device_id:
            device_id = data['paras']['id']
        if not device_id:
            logger.error("未提供设备 ID")
            return jsonify({'status': 'error', 'message': '未提供设备 ID'}), 400

        device = Device.query.filter_by(id=device_id).first()
        if not device:
            logger.error(f"设备 ID {device_id} 未找到")
            return jsonify({'status': 'error', 'message': '设备未找到'}), 404

        command_data = {k: data[k] for k in data if k in valid_keys and k != 'id'}
        command_type = 'set_rgb' if any(k in command_data for k in ['led_red', 'led_green', 'led_blue']) else \
            list(command_data.keys())[0] if command_data else 'unknown'
        device_command = DeviceCommand(
            device_id=device_id,
            user_id=current_user.id if current_user.is_authenticated else None,  # 假设使用 flask_login
            command_type=command_type,
            command_data=command_data,
            status='pending'
        )
        db.session.add(device_command)
        logger.info(
            f"已添加 DeviceCommand 记录: {device_command.id}, command_type: {command_type}, command_data: {command_data}")

        # 提交命令记录到数据库
        db.session.commit()
        temp_command = {
            "paras": {},
            "service_id": "Switch",
            "command_name": "control",
        }

        for key in data:
            if key in valid_keys:
                if key in ['led_red', 'led_blue', 'led_green', 'id']:
                    try:
                        value = int(data[key])
                        if not 0 <= value <= 255:
                            logger.error(f"{key} 值必须在0-255之间")
                            return jsonify({'status': 'error', 'message': f'{key} 值必须在0-255之间'}), 400
                        temp_command['paras'][key] = value
                    except ValueError:
                        logger.error(f"{key} 必须是整数")
                        return jsonify({'status': 'error', 'message': f'{key} 必须是整数'}), 400
                else:
                    temp_command['paras'][key] = bool(data[key])
        print("temp_command", temp_command)
        # 确保命令完整

        command = {
            "paras": {
                'gather': temp_command['paras'].get('gather', True),
                'open_fan': temp_command['paras'].get('open_fan', False),
                'open_water': temp_command['paras'].get('open_water', False),
                'open_led': temp_command['paras'].get('open_led', False),
                'led_red': temp_command['paras'].get('led_red', 100),
                'led_blue': temp_command['paras'].get('led_blue', 100),
                'led_green': temp_command['paras'].get('led_green', 100),
                'id': temp_command['paras'].get('id', device_id)
            },
            "service_id": "Switch",
            "command_name": "control",
        }
        logger.info(f"更新后的命令: {command}")

        # 发布控制指令
        success = set_device_properties(command)
        if success:
            updated_keys = list(data.keys())
            logger.info(f"{updated_keys} 参数已成功发送！")
            return jsonify({'status': 'success', 'message': f'{updated_keys} 参数已更新'})
        else:
            db.session.rollback()
            logger.error("设备控制失败！")
            return jsonify({'status': 'error', 'message': '设备控制失败'}), 500

    except Exception as e:
        db.session.rollback()
        logger.error(f"错误: {str(e)}")
        return jsonify({'status': 'error', 'message': str(e)}), 500


# 智能规则接口
@bp.route('/auto_rules', methods=['GET', 'POST', 'DELETE'])
def manage_rules():
    global auto_rules

    if request.method == 'POST':
        new_rule = request.json

        # 验证请求数据
        required_fields = ['name', 'sensor', 'operator', 'threshold', 'action']
        if not all(field in new_rule for field in required_fields):
            return jsonify({'status': 'error', 'message': '缺少必要的字段'}), 400

        # 生成唯一 ID
        rule_id = str(uuid.uuid4())
        new_rule['id'] = rule_id

        auto_rules.append(new_rule)
        print("智能规则列表:", auto_rules)
        # 检查是否需要立即执行规则
        check_and_execute_rules()

        return jsonify({'id': rule_id})

    elif request.method == 'DELETE':
        rule_id = request.args.get('id')
        auto_rules = [rule for rule in auto_rules if rule['id'] != rule_id]
        return jsonify({'status': 'deleted'})

    # GET 请求，返回所有规则
    return jsonify(auto_rules)


# 定时任务接口
@bp.route('/schedules', methods=['GET', 'POST', 'DELETE'])
def manage_schedules():
    return jsonify(scheduled_tasks)
